package com.hzxgs.tracelogstarter.trace;

import cn.hutool.http.HttpInterceptor;
import cn.hutool.http.HttpRequest;
import com.hzxgs.tracelogstarter.properties.TraceProperties;
import com.hzxgs.tracelogstarter.util.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ConditionalOnClass(value = { HttpInterceptor.class })
@Slf4j
public class HutoolHttpTraceInterceptor implements HttpInterceptor<HttpRequest> {

    @Resource
    private TraceProperties traceProperties;

    @Override
    public void process(HttpRequest request) {
        if (traceProperties.getEnable()) {
            try {
                request.header(TraceUtils.TRACE_ID_HEADER, TraceUtils.getTraceId());
                request.header(TraceUtils.SPAN_ID_HEADER, TraceUtils.getNextSpanId());
            } catch (Exception e) {
                log.error("hutool Http 透传traceId失败", e);
                e.printStackTrace();
            }
        }
    }
}
